<template>
  <div class="echarts-container">
    <div ref="chart" class="chart"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { onMounted, ref, onBeforeUnmount } from 'vue';
import service from "@/utils/request.js";
import { statisticsWebSocket } from '@/api/fishRecognition'
export default {
  name: 'StatsChart',
  setup() {
    const chart = ref(null);
    let myChart = null;
    const resizeHandler = () => {
      if (myChart) myChart.resize();
    };
    const stats = ref({})
    onMounted(() => {
      // 绑定消息接收回调
      statisticsWebSocket.onMessage = (data) => {
        // 根据API文档，data.data 应为 { onlineUsers, todayRecognitions, totalRecognitions, totalImages }
        stats.value = data.data || {}
        if (myChart) {
          myChart.setOption({
            series: [{
              data: [
                {
                  value: stats.value.onlineUsers || 0,
                  itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                      { offset: 0, color: '#00c6ff' },
                      { offset: 1, color: '#0072ff' },
                    ])
                  },
                },
                {
                  value: stats.value.todayRecognitions || 0,
                  itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                      { offset: 0, color: '#ff8a00' },
                      { offset: 1, color: '#ff4d00' },
                    ])
                  },
                },
                {
                  value: stats.value.totalImages || 0,
                  itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                      { offset: 0, color: '#6a11cb' },
                      { offset: 1, color: '#2575fc' },
                    ])
                  },
                },
                {
                  value: stats.value.totalRecognitions || 0,
                  itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                      { offset: 0, color: '#11998e' },
                      { offset: 1, color: '#38ef7d' },
                    ])
                  },
                },
              ]
            }]
          });
        }
      }
      // 尝试连接（如果自动连接逻辑没有在客户端初始化时触发的话）
      statisticsWebSocket.connect()
      myChart = echarts.init(chart.value);
      const option = {
        backgroundColor: 'rgba(10, 26, 58, 0)', // 最后一个参数是透明度（0-1），0 为完全透明，1 为不透明
        title: {
          show: false,
          text: '统计数量',
          left: 'center',
          top: 20,
          textStyle: {
            color: '#fff',
            fontSize: 18,
            fontWeight: 'normal',
          },
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true,
          top: 80,
        },
        xAxis: {
          type: 'category',
          data: ['当前在线用户数', '今日上传识别数', '累计上传识别数', '已有上传图片'],
          axisLine: { lineStyle: { color: '#4a8fe7' } },
          axisLabel: { color: '#fff', fontSize: 16, interval: 0, rotate: 0 },
          axisTick: { alignWithLabel: true },
        },
        yAxis: {
          type: 'value',
          min: 0,
          max: 750,
          interval: 150,
          axisLine: { show: true, lineStyle: { color: '#4a8fe7' } },
          axisLabel: { color: '#fff', formatter: '{value}', fontSize: 16 },
          splitLine: { lineStyle: { color: 'rgba(74, 143, 231, 0.2)' } },
        },
        series: [
          {
            name: '统计量',
            type: 'bar',
            barWidth: '40%',
            data: [
              {
                value: stats.value.onlineUsers || 0,
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#00c6ff' },
                    { offset: 1, color: '#0072ff' },
                  ]),
                },
              },
              {
                value: stats.value.todayRecognitions || 0,
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#ff8a00' },
                    { offset: 1, color: '#ff4d00' },
                  ]),
                },
              },
              {
                value: stats.value.totalImages || 0,
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#6a11cb' },
                    { offset: 1, color: '#2575fc' },
                  ]),
                },
              },
              {
                value: stats.value.totalRecognitions || 0,
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#11998e' },
                    { offset: 1, color: '#38ef7d' },
                  ]),
                },
              },
            ],
            label: {
              show: true,
              position: 'top',
              formatter: '{c}',
              color: '#fff',
            },
          },
        ],
      };
      myChart.setOption(option);
      window.addEventListener('resize', resizeHandler);
    });

    onBeforeUnmount(() => {
      window.removeEventListener('resize', resizeHandler);
      if (statisticsWebSocket) {
        statisticsWebSocket.disconnect();
      }
      if (myChart) {
        myChart.dispose();
        myChart = null;
      }
    });
    return {
      chart,
    };
  },
};
</script>

<style scoped>
.echarts-container {
  width: 100%;
  height: 400px;
  background-color: rgba(0, 0, 0, 0.1);
  border-radius: 10px;
  /* padding: 20px; */
  box-sizing: border-box;
  position: relative;
  bottom: 60px;
}

.chart {
  width: 100%;
  height: 100%;
  /* 填满父容器 */
  margin: 0 auto;
}
</style>
